package com.kt.uokos.yimo.wx.controller;

import com.kt.uokos.yimo.dao.Cart;
import com.kt.uokos.yimo.dao.GoodsProduct;
import com.kt.uokos.yimo.dao.Product;
import com.kt.uokos.yimo.service.CartService;
import com.kt.uokos.yimo.service.GoodsProductService;
import com.kt.uokos.yimo.service.ProductService;
import com.kt.uokos.yimo.util.JacksonUtil;
import com.kt.uokos.yimo.util.ResponseUtil;
import com.kt.uokos.yimo.wx.annocation.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: TODO
 * @className: WxCartController.java
 * @author: Kang Hao
 * @date: 2022/4/23 20:24
 **/


@RestController
@RequestMapping("/wx/cart/")
@Validated
public class WxCartController {

    @Resource
    private CartService cartService;

    @Resource
    private ProductService productService;

    @Resource
    private GoodsProductService goodsProductService;





    @GetMapping("index")
    public Object index(@LoginUser Integer userId){
        if (userId == null){
            return ResponseUtil.unlogin();
        }
        List<Cart> cartListOld = cartService.queryByUid(userId);
        List<Cart> cartList = new ArrayList<>();


        //判断用户购物车中的商品是否过期或下架
        for (Cart cart : cartListOld){
            Product product = productService.queryByProId(cart.getGoodsId());
            if (product == null || !product.getIsOnSale()){
                cartService.deletedById(cart.getId());
                return ResponseUtil.fail(404,"该物品已下架");
            }else {
                cartList.add(cart);
            }
        }

        //有几件商品
        Integer goodsCount = 0;
        //商品价格的总数
        BigDecimal goodsCountPrice = new BigDecimal(0.00);
        //判断其商品是否处在被选择的状态
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsCountPrice = new BigDecimal(0.00);

        //遍历并进行统计
        for (Cart cart : cartList) {
            goodsCount += cart.getNumber();
            goodsCountPrice = goodsCountPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            if (cart.getChecked())  {
                checkedGoodsCount += cart.getNumber();
                checkedGoodsCountPrice = checkedGoodsCountPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }

        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsCountPrice);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsCountPrice);

        Map<String, Object> map = new HashMap<>();
        map.put("cartList", cartList);
        map.put("cartTotal", cartTotal);

        return ResponseUtil.ok(map);
    }


    @PostMapping("checked")
    public Object checked(@LoginUser Integer userId, @RequestBody String body){
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (body == null) {
            return ResponseUtil.errs();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");
        if (productIds == null) {
            return ResponseUtil.errs();
        }

        Integer checkValue = JacksonUtil.parseInteger(body, "isChecked");
        if (checkValue == null) {
            return ResponseUtil.errs();
        }
        Boolean isChecked = (checkValue == 1);

        cartService.updateChecked(userId, productIds, isChecked);
        return index(userId);
    }



    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId, @RequestBody String body){

        if (userId == null){
            return ResponseUtil.unlogin();
        }

        if (body == null){
            return ResponseUtil.errs();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");

        if (productIds == null|| productIds.size() == 0){
            return ResponseUtil.errs();
        }

        cartService.delete(userId,productIds);
        return index(userId);
    }


    @PostMapping("add")
    public Object add(@LoginUser Integer userId,@RequestBody Cart cart){

        if (userId == null){
            return ResponseUtil.unlogin();
        }

        if (cart == null){
            return ResponseUtil.errs();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }
        if(number <= 0){
            return ResponseUtil.badArgument();
        }


        //判断此商品是否售空或下架
        Product product = productService.queryByProId(goodsId);
        if (product == null || !product.getIsOnSale()){
            return ResponseUtil.fail(404,"商品已下架");
        }
        //商品规格
        GoodsProduct goodsProduct = goodsProductService.queryById(productId);
        //判断购物车中是否有此规格商品
        Cart existCart = cartService.queryExist(userId, goodsId, productId);

        if (existCart == null ) {


            //判断数据库中此规格是否还有
            if (goodsProduct == null || number >= goodsProduct.getNumber()) {
                return ResponseUtil.fail(404, "库存不足");
            }
            cart.setGoodsSn(product.getGoodsSn());
            cart.setGoodsName((product.getName()));
            if(StringUtils.isEmpty(goodsProduct.getUrl())){
                cart.setPicUrl(product.getPicUrl());
            }
            else{
                cart.setPicUrl(goodsProduct.getUrl());
            }
            cart.setPrice(goodsProduct.getPrice());
            cart.setSpecifications(goodsProduct.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        }else {
            //在购物车中将此商品的数量修改
            int num = existCart.getNumber() + number;
            if (num > goodsProduct.getNumber()) {
                return ResponseUtil.fail(404, "库存不足");
            }
            existCart.setNumber((short) num);
        }

        return count(userId);
    }

    //与添加到购物车思路大致相同，只是不再需要对比购物车
    @PostMapping("fastadd")
    public Object fastadd(@LoginUser Integer userId,@RequestBody Cart cart){

        if (userId == null){
            return ResponseUtil.unlogin();
        }

        if (cart == null){
            return ResponseUtil.errs();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }
        if(number <= 0){
            return ResponseUtil.badArgument();
        }


        Product product = productService.queryByProId(goodsId);
        if (product == null || !product.getIsOnSale()){
            return ResponseUtil.fail(404,"商品已下架");
        }



        GoodsProduct goodsProduct = goodsProductService.queryById(productId);
        //判断购物车中是否有此规格商品
        Cart existCart = cartService.queryExist(userId, goodsId, productId);

        if (existCart == null ) {


            //判断数据库中此规格是否还有
            if (goodsProduct == null || number >= goodsProduct.getNumber()) {
                return ResponseUtil.fail(404, "库存不足");
            }
            cart.setGoodsSn(product.getGoodsSn());
            cart.setGoodsName((product.getName()));
            if(StringUtils.isEmpty(goodsProduct.getUrl())){
                cart.setPicUrl(product.getPicUrl());
            }
            else{
                cart.setPicUrl(goodsProduct.getUrl());
            }
            cart.setPrice(goodsProduct.getPrice());
            cart.setSpecifications(goodsProduct.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        }else {
            int num = number;
            if (num > goodsProduct.getNumber()) {
                return ResponseUtil.fail(404, "库存不足");
            }
            existCart.setNumber((short) num);
        }

        return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
    }

    @GetMapping("goodscount")
    public Object count(@LoginUser Integer userId){
        if (userId==null){
            return ResponseUtil.ok(0);
        }
        Integer count = cartService.countByUid(userId);
        return ResponseUtil.ok(count);
    }
}
